// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

// Copyright (C) 2013-2014	JoostinOnline

#include <gccore.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ogc/wiilaunch.h>

#include "debug.h"
#include "title.h"

s8 TITLE_LaunchTitle(const char *uppertitle, const char *lowertitle) {
	/*
	Return is:
	TITLE_ENODIR	:	Channel directory does not exist
	TITLE_ENOLAUNCH	:	Directory exists, but channel failed to launch
	TITLE_ELENGTH	:	title is not 4 or 8 characters long
	TITLE_ENULL		:	title is NULL
	*/

	u32 num = 0; // for checking if directory exists (ISFS_ReadDir)
	char directory[25] = {0}; // end result is the title directory
	u32 len; // length of lowertitle to determine if it is hex or ascii
	char buffer[8] = {0};
	Debug("------------------------------------------");
	
	if ((uppertitle == NULL) || (lowertitle == NULL)) {
		Debug("Error: title is NULL");
		return TITLE_ENULL;
	}
	Debug("Launching title %s", lowertitle);
	len = strlen(lowertitle);
		
	if ((len != 8) && (len != 4)) {
		Debug("Error: Title ID %s is %u characters long", lowertitle, len);
		return TITLE_ELENGTH;
	}
	if (len == 4) {
		sprintf(buffer, "%02x%02x%02x%02x", lowertitle[0], lowertitle[1], lowertitle[2], lowertitle[3]);
		Debug("Converted %s to %s", lowertitle, buffer);
	}
	
	sprintf(directory, "/title/%s/%s", uppertitle, lowertitle);
	
	u32 hexupper = strtoul(uppertitle, NULL, 16);
	u32 hexlower = strtoul(buffer, NULL, 16);

	if (ISFS_ReadDir(directory, NULL, &num))
	{
		Debug("Error: Directory %s was not found", directory);
		return TITLE_ENODIR;
	}
	WII_LaunchTitle(TITLE_ID(hexupper, hexlower));
	// If the following code is reached, launch failed
	Debug("Error: Directory %s was found, but channel was not installed", directory);
	return TITLE_ENOLAUNCH;
} // LaunchTitle

inline void TITLE_LaunchAllTypes(const char *lowertitle) {
	TITLE_LaunchTitle(TITLE_CUSTOM, lowertitle);
	TITLE_LaunchTitle(TITLE_SYSTEM, lowertitle);
	TITLE_LaunchTitle(TITLE_GAME, lowertitle);
	TITLE_LaunchTitle(TITLE_HIDDEN, lowertitle);
} // LaunchAllTypes
